package com.lu.aio;

import cn.hutool.core.util.CharsetUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/**
 * @program lu-netty
 * @description:
 * @author: zhanglu
 * @create: 2022-06-10 17:08:00
 */
public abstract class ChannelAdapter implements CompletionHandler<Integer, Object> {

    private AsynchronousSocketChannel channel;
    private String charset;

    public ChannelAdapter(AsynchronousSocketChannel channel, String charset){
        this.channel = channel;
        this.charset = charset;
        //处理器创建完成-通知处理逻辑(发送一个通知)
        if(channel.isOpen()){
            channelActive(new ChannelHandler(channel, charset));
        }
    }

    /**
     * 事件(读)-处理器
     * @param result
     * @param obj
     */
    @Override
    public void completed(Integer result, Object obj) {
        ByteBuffer buffer = (ByteBuffer) obj;
        if(result == -1){
            try {
                channelInactive(new ChannelHandler(channel, charset));
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        buffer.flip();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        try {
            channelRead(new ChannelHandler(channel, charset), new String(bytes, charset));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        buffer.clear();
    }

    @Override
    public void failed(Throwable exc, Object attachment) {
        exc.printStackTrace();
    }

    //连接通知 - 处理器
    protected abstract void channelActive(ChannelHandler ctx);

    //通道未激活
    protected abstract void channelInactive(ChannelHandler ctx);

    //读取消息 - 处理器
    protected abstract void channelRead(ChannelHandler ctx, Object msg);


}
